// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.CustomExcelExport;
import com.fowo.api.common.excel.CustomExcelHandler;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.excel.TemplateModelBuildEventListener;
import com.fowo.api.common.model.ImportRow;
import com.fowo.api.common.model.JoinModel;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.ContextHolder;
import com.fowo.api.common.util.DateUtils;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.common.util.SheetUtils;
import com.fowo.api.entity.AmazonOrderList;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.mapper.AmazonOrderListMapper;
import com.fowo.api.mapper.AmazonOrderListProductMapper;
import com.fowo.api.mapper.ShopInfoMapper;
import com.fowo.api.model.amazon.order.list.AmazonOrderListAolSignPromotionAction;
import com.fowo.api.model.amazon.order.list.AmazonOrderListExcelPo;
import com.fowo.api.model.amazon.order.list.AmazonOrderListImportPo;
import com.fowo.api.model.amazon.order.list.AmazonOrderListItemVo;
import com.fowo.api.model.amazon.order.list.AmazonOrderListSearchParamPo;
import com.fowo.api.model.amazon.order.list.AmazonOrderListVo;
import com.fowo.api.model.amazon.order.list.constant.AmazonOrderListFulfillmentChannelEnums;
import com.fowo.api.model.amazon.order.list.constant.AmazonOrderListIsBusinessOrderEnums;
import com.fowo.api.model.amazon.order.list.constant.AmazonOrderListIsMcfOrderEnums;
import com.fowo.api.model.amazon.order.list.constant.AmazonOrderListIsReplacedOrderEnums;
import com.fowo.api.model.amazon.order.list.constant.AmazonOrderListIsReplacementOrderEnums;
import com.fowo.api.model.amazon.order.list.constant.AmazonOrderListIsReturnEnums;
import com.fowo.api.model.amazon.order.list.constant.AmazonOrderListOrderStatusEnums;
import com.fowo.api.model.amazon.order.list.product.AmazonOrderListProductSearchParamPo;
import com.fowo.api.model.shop.info.ShopInfoItemVo;
import com.fowo.api.model.shop.info.ShopInfoSearchParamPo;
import com.fowo.api.service.AmazonOrderListProductService;
import com.fowo.api.service.AmazonOrderListService;
import com.fowo.api.sys.component.ExecuteScriptEngine;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.sys.entity.SysImportTemplate;
import com.fowo.api.sys.service.FileService;
import com.fowo.api.sys.service.SysImportTemplateService;
import com.fowo.api.user.model.JwtUserInfo;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 亚马逊订单 服务实现类
 * @author 蜂窝蜜造平台 配置人：陈新新，李玉娇
 */
@Service
@Slf4j
@DS("ds24")
public class AmazonOrderListServiceImpl
  extends ServiceImpl<AmazonOrderListMapper, AmazonOrderList>
  implements AmazonOrderListService {

  /** 引用字段排序字段名转换信息 */
  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>() {
    {
      put("shopIdShopName", "si.`shop_name`");
    }
  };
  // 导出时单次查询最大记录数
  protected static final int EXPORT_QUERY_MAX_SIZE = 1000;
  // 支持导出的最大记录数(1048576 为 Excel 支持的最大行数)
  protected static final long EXPORT_MAX_SIZE = 1048575;

  @Resource
  protected AmazonOrderListProductService amazonOrderListProductService;

  @Resource
  protected ShopInfoMapper shopInfoMapper;

  @Resource
  protected FileService fileService;

  @Resource
  protected SysImportTemplateService importTemplateService;

  @Resource
  private CustomExcelExport customExcelExport;

  @Resource
  private WorkFlowService workFlowService;

  @Resource
  private ExecuteScriptEngine executeScriptEngine;

  @Autowired(required = false)
  protected AmazonOrderListAolSignPromotionAction amazonOrderListAolSignPromotionAction;

  @Resource
  protected Validator validator;

  /**
   * 创建亚马逊订单
   * @param model 亚马逊订单
   * @return 新数据的主键
   */
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(AmazonOrderListVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    AmazonOrderList entity = new AmazonOrderList();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.save(entity)) {
      model.setId(entity.getId());
      updateAllChilds(model);
      return entity.getId();
    }
    throw new Exception("亚马逊订单保存失败");
  }

  /**
   * 更新所有子表
   * @param model 亚马逊订单
   */
  protected void updateAllChilds(AmazonOrderListVo model) throws Exception {
    if (model.getList() != null) {
      amazonOrderListProductService.saveAllByParentAmazonOrderList(
        model.getId(),
        model.getList()
      );
    }
  }

  /**
   * 更新亚马逊订单
   * @param model 亚马逊订单
   * @return 更新是否成功
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(AmazonOrderListVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    AmazonOrderList entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("亚马逊订单不存在");
    }
    BeanUtils.copyProperties(
      model,
      entity,
      "id",
      "createTime",
      "createUser",
      "lastUpdateTime",
      "lastUpdateUser"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      updateAllChilds(model);
      return true;
    }
    return false;
  }/**
   * 更新亚马逊订单（带空值）
   * @param model 亚马逊订单
   * @return 更新是否成功
   */

  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(AmazonOrderListVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    AmazonOrderList entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("亚马逊订单不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(AmazonOrderList::getLastUpdateTime, model.getLastUpdateTime())
      .set(AmazonOrderList::getSellerName, model.getSellerName())
      .set(AmazonOrderList::getCountry, model.getCountry())
      .set(AmazonOrderList::getAmazonOrderId, model.getAmazonOrderId())
      .set(AmazonOrderList::getBuyerName, model.getBuyerName())
      .set(AmazonOrderList::getBuyerEmail, model.getBuyerEmail())
      .set(AmazonOrderList::getOrderTotalAmount, model.getOrderTotalAmount())
      .set(AmazonOrderList::getPurchaseDateLocal, model.getPurchaseDateLocal())
      .set(AmazonOrderList::getRemark, model.getRemark())
      .set(
        AmazonOrderList::getRequestCommentStatus,
        model.getRequestCommentStatus()
      )
      .set(AmazonOrderList::getOrderStatus, model.getOrderStatus())
      .set(AmazonOrderList::getEarliestShipDate, model.getEarliestShipDate())
      .set(
        AmazonOrderList::getEarliestShipDateUtc,
        model.getEarliestShipDateUtc()
      )
      .set(AmazonOrderList::getLastUpdateUser, model.getLastUpdateUser())
      .set(
        AmazonOrderList::getFulfillmentChannel,
        model.getFulfillmentChannel()
      )
      .set(AmazonOrderList::getPostalCode, model.getPostalCode())
      .set(AmazonOrderList::getPhone, model.getPhone())
      .set(AmazonOrderList::getIsMcfOrder, model.getIsMcfOrder())
      .set(AmazonOrderList::getIsAssessed, model.getIsAssessed())
      .set(
        AmazonOrderList::getOrderTotalCurrencyCode,
        model.getOrderTotalCurrencyCode()
      )
      .set(AmazonOrderList::getSalesChannel, model.getSalesChannel())
      .set(AmazonOrderList::getTrackingNumber, model.getTrackingNumber())
      .set(AmazonOrderList::getRefundAmount, model.getRefundAmount())
      .set(
        AmazonOrderList::getPurchaseDateLocalUtc,
        model.getPurchaseDateLocalUtc()
      )
      .set(AmazonOrderList::getShipmentDate, model.getShipmentDate())
      .set(AmazonOrderList::getShipmentDateUtc, model.getShipmentDateUtc())
      .set(AmazonOrderList::getShipmentDateLocal, model.getShipmentDateLocal())
      .set(AmazonOrderList::getLastUpdateDate, model.getLastUpdateDate())
      .set(AmazonOrderList::getLastUpdateDateUtc, model.getLastUpdateDateUtc())
      .set(AmazonOrderList::getPostedDate, model.getPostedDate())
      .set(AmazonOrderList::getPostedDateUtc, model.getPostedDateUtc())
      .set(AmazonOrderList::getPurchaseDate, model.getPurchaseDate())
      .set(AmazonOrderList::getPurchaseDateUtc, model.getPurchaseDateUtc())
      .set(AmazonOrderList::getGmtModified, model.getGmtModified())
      .set(AmazonOrderList::getGmtModifiedUtc, model.getGmtModifiedUtc())
      .set(AmazonOrderList::getShipServiceLevel, model.getShipServiceLevel())
      .set(AmazonOrderList::getAddressLine1, model.getAddressLine1())
      .set(AmazonOrderList::getName, model.getName())
      .set(AmazonOrderList::getIsReturn, model.getIsReturn())
      .set(
        AmazonOrderList::getIsReplacementOrder,
        model.getIsReplacementOrder()
      )
      .set(AmazonOrderList::getIsReplacedOrder, model.getIsReplacedOrder())
      .set(AmazonOrderList::getIsBusinessOrder, model.getIsBusinessOrder())
      .set(AmazonOrderList::getShopId, model.getShopId())
      .set(AmazonOrderList::getShopCode, model.getShopCode())
      .eq(AmazonOrderList::getId, model.getId())
      .update();
    if (isOk) {
      updateAllChilds(model);
    }
    return isOk;
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(AmazonOrderListSearchParamPo search) {
    return false;
  }

  /**
   * 批量删除指定主键列表关联的所有子表数据(此方法不包括事务，必须由其它已包括事务的方法调用)
   */
  protected void batchDeleteChilds(List<Long> ids) throws Exception {
    // 处理子表字段 订单子表(list) 对应的对象
    AmazonOrderListProductSearchParamPo listSearchParam =
      new AmazonOrderListProductSearchParamPo();
    listSearchParam.setDisableDataPremissions(true);
    listSearchParam.setParentAmazonOrderListInList(ids);
    AmazonOrderListProductMapper localAmazonOrderListProductMapper =
      ContextHolder
        .getApplicationContext()
        .getBean(AmazonOrderListProductMapper.class);
    listSearchParam.applySqlSegments();
    List<Long> listIdList = localAmazonOrderListProductMapper.searchIds(
      listSearchParam
    );
    if (!listIdList.isEmpty()) {
      AmazonOrderListProductService localAmazonOrderListProductService =
        ContextHolder
          .getApplicationContext()
          .getBean(AmazonOrderListProductService.class);
      localAmazonOrderListProductService.batchDelete(listIdList);
    }
  }

  /**
   * 删除亚马逊订单
   * @param id 亚马逊订单的主键
   * @return 删除是否成功
   */
  @Override
  public boolean delete(Long id) throws Exception {
    batchDeleteChilds(Collections.singletonList(id));
    return this.removeById(id);
  }

  /**
   * 批量删除亚马逊订单
   * @param ids 亚马逊订单的主键列表
   * @return 删除是否成功
   */
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    batchDeleteChilds(ids);
    return baseMapper.deleteBatchIds(ids) > 0;
  }

  /**
   * 导入单行处理
   * @param row 要导入的行
   * @param rowNumber 所在行号
   * @param vo 输出VO,可空
   * @param variables 变量池，用于在一次导入过程中保存临时信息
   * @param allowOverrides 允许覆盖
   * @return 导入行对象
   */
  protected ImportRow<AmazonOrderListImportPo> excelToImportRow(
    AmazonOrderListImportPo row,
    Integer rowNumber,
    AmazonOrderListVo vo,
    Map<String, Object> variables,
    boolean allowOverrides
  ) {
    ImportRow<AmazonOrderListImportPo> ir =
      new ImportRow<AmazonOrderListImportPo>();
    ir.setRowNumber(rowNumber);
    ir.setRow(row);
    if (SheetUtils.isAllFieldsEmpty(row)) {
      ir.setEmptyRow(true);
      ir.addError("", "空行");
      return ir;
    }
    final Set<ConstraintViolation<AmazonOrderListImportPo>> validate =
      validator.validate(row);
    boolean isOutputVo = vo != null;
    if (!isOutputVo) {
      vo = new AmazonOrderListVo();
    }
    BeanUtils.copyProperties(row, vo);
    // 收集基本校验错误
    ir.initErrors(validate, AmazonOrderListImportPo.class);

    // 一般数据处理
    if (StringUtils.hasText(row.getOrderStatus())) {
      vo.setOrderStatus(
        AmazonOrderListOrderStatusEnums.toValue(row.getOrderStatus())
      );
      if (vo.getOrderStatus() == null) {
        ir.addError("orderStatus", "状态只能是：“Unshipped”, “Shipped”");
      }
    }
    if (StringUtils.hasText(row.getFulfillmentChannel())) {
      vo.setFulfillmentChannel(
        AmazonOrderListFulfillmentChannelEnums.toValue(
          row.getFulfillmentChannel()
        )
      );
      if (vo.getFulfillmentChannel() == null) {
        ir.addError("fulfillmentChannel", "发货渠道只能是：“AFN”, “MFN”");
      }
    }
    if (StringUtils.hasText(row.getIsMcfOrder())) {
      vo.setIsMcfOrder(
        AmazonOrderListIsMcfOrderEnums.toValue(row.getIsMcfOrder())
      );
      if (vo.getIsMcfOrder() == null) {
        ir.addError(
          "isMcfOrder",
          "是否多渠道订单只能是：“多渠道订单”, “普通订单”"
        );
      }
    }
    vo.setIsAssessed(SheetUtils.tryToInteger(row.getIsAssessed()));
    if (StringUtils.hasText(row.getIsReturn())) {
      vo.setIsReturn(AmazonOrderListIsReturnEnums.toValue(row.getIsReturn()));
      if (vo.getIsReturn() == null) {
        ir.addError("isReturn", "退款状态只能是：“退款”, “未退款”, “退款完成”");
      }
    }
    if (StringUtils.hasText(row.getIsReplacementOrder())) {
      vo.setIsReplacementOrder(
        AmazonOrderListIsReplacementOrderEnums.toValue(
          row.getIsReplacementOrder()
        )
      );
      if (vo.getIsReplacementOrder() == null) {
        ir.addError("isReplacementOrder", "是否换货订单只能是：“是”, “否”");
      }
    }
    if (StringUtils.hasText(row.getIsReplacedOrder())) {
      vo.setIsReplacedOrder(
        AmazonOrderListIsReplacedOrderEnums.toValue(row.getIsReplacedOrder())
      );
      if (vo.getIsReplacedOrder() == null) {
        ir.addError("isReplacedOrder", "是否已换货只能是：“换货”");
      }
    }
    if (StringUtils.hasText(row.getIsBusinessOrder())) {
      vo.setIsBusinessOrder(
        AmazonOrderListIsBusinessOrderEnums.toValue(row.getIsBusinessOrder())
      );
      if (vo.getIsBusinessOrder() == null) {
        ir.addError("isBusinessOrder", "是否为B2B订单只能是：“B2B”");
      }
    }
    // 处理关联字段“店铺id”
    if (
      !SheetUtils.isBlank(row.getShopIdShopName()) &&
      SheetUtils.isBlank(row.getShopId())
    ) {
      ShopInfoSearchParamPo shopIdSearchParam = new ShopInfoSearchParamPo();
      shopIdSearchParam.setLimit(2); // 最大只返回二行记录
      shopIdSearchParam.setShopNameEq(SheetUtils.trim(row.getShopIdShopName()));
      shopIdSearchParam.applySqlSegments();
      List<ShopInfoItemVo> shopIdMatches = shopInfoMapper.search(
        shopIdSearchParam
      );
      if (shopIdMatches.size() == 0) {
        ir.addError("shopIdShopName", "未能在店铺中找到匹配的数据");
      } else if (shopIdMatches.size() > 1) {
        ir.addError("shopIdShopName", "关联不唯一，在店铺中找到多个匹配的数据");
      } else {
        vo.setShopId(shopIdMatches.get(0).getId());
        //20230706 调整
        final Map apiParams = MapUtil
          .builder()
          .put("id", shopIdMatches.get(0).getId())
          .put("fromObjectName", "AmazonOrderList")
          .put("fromObjectId", vo.getId())
          .put("fromField", "shopId")
          .build();

        final List<JoinModel> joinModels = CollUtil.newArrayList(
          JoinModel
            .builder()
            .sourceFieldName("shopName")
            .sourceType("field")
            .sourceApi(null)
            .targetFieldName("sellerName")
            .rowFieldName("sellerName")
            .apiParams(apiParams)
            .required(false)
            .importIgnore(false)
            .build(),
          JoinModel
            .builder()
            .sourceFieldName("shopCode")
            .sourceType("field")
            .sourceApi(null)
            .targetFieldName("shopCode")
            .rowFieldName("shopCode")
            .apiParams(apiParams)
            .required(false)
            .importIgnore(false)
            .build()
        );
        SheetUtils.joinHandle(
          null,
          ir,
          null,
          vo,
          CollUtil.getFirst(shopIdMatches),
          joinModels
        );
      }
    }

    return ir;
  }

  /**
   * 导入预览
   * @param sysFile 已上传到系统的文件
   * @param templateId 要使用的模版编号
   * @param allowOverrides 允许覆盖
   */
  @Override
  public List<ImportRow<AmazonOrderListImportPo>> importPreview(
    SysFile sysFile,
    Long templateId,
    boolean allowOverrides
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    Map<String, Object> variables = new HashMap<>();
    try (InputStream in = fileService.read(sysFile)) {
      List<ImportRow<AmazonOrderListImportPo>> rows = new ArrayList<>();

      // 读取 Excel 到 rows
      EasyExcel
        .read(in)
        .useDefaultListener(false)
        .registerReadListener(
          new TemplateModelBuildEventListener<>(
            AmazonOrderListImportPo.class,
            importTemplate
          ) {
            @Override
            public void invokeRow(
              AmazonOrderListImportPo row,
              AnalysisContext cxt
            ) {
              AmazonOrderListVo vo = new AmazonOrderListVo();
              ImportRow<AmazonOrderListImportPo> ir = excelToImportRow(
                row,
                cxt.readRowHolder().getRowIndex(),
                vo,
                variables,
                allowOverrides
              );
              if (ir.isEmptyRow()) {
                return;
              }
              if (allowOverrides) {
                // FIXME: 未在平台上配置此对象《作为导入唯一识别》的《逻辑分组》配置，无法处理更新模式
              }
              rows.add(ir);
            }
          }
        )
        .sheet()
        .doRead();

      return rows;
    }
  }

  /**
   * 完成导入
   * @param rows 预导入的行信息
   */
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void importDone(
    List<ImportRow<AmazonOrderListImportPo>> rows,
    Long templateId
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    String sysImportBatchNo = StrUtil.concat(
      true,
      DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_MS_PATTERN),
      IdUtil.nanoId(4)
    );
    List<Long> importedIdList = new ArrayList<>();
    Map<String, Object> variables = new HashMap<>();
    for (int i = 0; i < rows.size(); i++) {
      ImportRow<AmazonOrderListImportPo> row = rows.get(i);
      Long updateId = row.getUpdateId();
      AmazonOrderListVo vo = new AmazonOrderListVo();
      row =
        excelToImportRow(row.getRow(), row.getRowNumber(), vo, variables, true);
      if (row.getErrors() != null && row.getErrors().size() > 0) {
        throw new RException(
          String.format(
            "第%d行（Excel第%d行）数据验证错误：%s",
            i + 1,
            row.getRowNumber(),
            row.getJoinErrorMessage()
          )
        );
      }
      if (updateId != null) {
        vo.setId(updateId);
      }
      SheetUtils.setSysImportTemplateName(
        vo,
        null == importTemplate ? "默认模板" : importTemplate.getTitle()
      );
      SheetUtils.setSysImportBatchNo(vo, sysImportBatchNo);
      if (updateId == null) {
        importedIdList.add(create(vo));
      } else {
        update(vo);
        importedIdList.add(vo.getId());
      }
    }
  }

  /**
   * 导出
   * @param templateId 使用模版（可以是 null 或 0 表示系统默认导出模版）
   * @param search 查询条件
   */
  @Override
  public void export(
    Long templateId,
    AmazonOrderListSearchParamPo search,
    HttpServletResponse response
  ) throws Exception {
    if (templateId != null && templateId > 0) {
      SysImportTemplate sysImportTemplate = importTemplateService.getById(
        templateId
      );
      if (sysImportTemplate == null) {
        throw new RException("所选的导出模版不可用");
      }
      CustomExcelExport.CustomExcelExportOptions exportOptions =
        new CustomExcelExport.CustomExcelExportOptions();
      exportOptions.setImportTemplate(sysImportTemplate);
      exportOptions.setSearchParam(search);
      exportOptions.setMainService(this);
      exportOptions.addFieldMappingOption(
        "orderStatus",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            AmazonOrderListOrderStatusEnums.toLabel((String) o)
          )
      );
      exportOptions.addFieldMappingOption(
        "fulfillmentChannel",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            AmazonOrderListFulfillmentChannelEnums.toLabel((String) o)
          )
      );
      exportOptions.addFieldMappingOption(
        "isReturn",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            AmazonOrderListIsReturnEnums.toLabel((String) o)
          )
      );
      exportOptions.addFieldMappingOption(
        "isReplacementOrder",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            AmazonOrderListIsReplacementOrderEnums.toLabel((String) o)
          )
      );
      exportOptions.addFieldMappingOption(
        "isReplacedOrder",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            AmazonOrderListIsReplacedOrderEnums.toLabel((String) o)
          )
      );
      exportOptions.addFieldMappingOption(
        "isBusinessOrder",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            AmazonOrderListIsBusinessOrderEnums.toLabel((String) o)
          )
      );
      exportOptions.addStringFields(
        "sellerName",
        "country",
        "amazonOrderId",
        "buyerName",
        "buyerEmail",
        "orderTotalAmount",
        "purchaseDateLocal",
        "remark",
        "orderStatus",
        "earliestShipDate",
        "earliestShipDateUtc",
        "fulfillmentChannel",
        "isReturn",
        "isReplacementOrder",
        "isReplacedOrder",
        "isBusinessOrder",
        "shopCode"
      );
      customExcelExport.run(exportOptions, response.getOutputStream());
      return;
    }
    search.setPageSize(EXPORT_QUERY_MAX_SIZE);
    int current = 1;
    List<AmazonOrderListExcelPo> items =
      new ArrayList<AmazonOrderListExcelPo>();
    while (true) {
      search.setCurrent(current);
      Page<AmazonOrderListItemVo> page = this.pageSearch(search);
      if (page.getTotal() > EXPORT_MAX_SIZE) {
        throw new RException("导出记录数超出限制！");
      }
      List<AmazonOrderListItemVo> list = page.getRecords();
      if (list.isEmpty()) {
        break;
      }
      for (AmazonOrderListItemVo item : list) {
        AmazonOrderListExcelPo excel = new AmazonOrderListExcelPo();
        BeanUtils.copyProperties(item, excel);
        excel.setOrderStatus(
          AmazonOrderListOrderStatusEnums.toLabel(item.getOrderStatus())
        );
        excel.setFulfillmentChannel(
          AmazonOrderListFulfillmentChannelEnums.toLabel(
            item.getFulfillmentChannel()
          )
        );
        excel.setIsReturn(
          AmazonOrderListIsReturnEnums.toLabel(item.getIsReturn())
        );
        excel.setIsReplacementOrder(
          AmazonOrderListIsReplacementOrderEnums.toLabel(
            item.getIsReplacementOrder()
          )
        );
        excel.setIsReplacedOrder(
          AmazonOrderListIsReplacedOrderEnums.toLabel(item.getIsReplacedOrder())
        );
        excel.setIsBusinessOrder(
          AmazonOrderListIsBusinessOrderEnums.toLabel(item.getIsBusinessOrder())
        );

        items.add(excel);
      }
      if (list.size() < EXPORT_QUERY_MAX_SIZE) {
        break;
      }
      current++;
    }

    String fileName = String.format(
      "亚马逊订单(%s).xlsx",
      DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
    );
    ResponseUtils.setAttachmentFileName(response, fileName);
    EasyExcel
      .write(response.getOutputStream())
      .registerWriteHandler(new CustomExcelHandler())
      .sheet()
      .head(AmazonOrderListExcelPo.class)
      .doWrite(items);
  }

  /**
   * 通过订单号查询亚马逊订单主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdByAmazonOrderId(String amazonOrderId) {
    return this.baseMapper.getIdByAmazonOrderId(amazonOrderId);
  }

  /**
   * 通过订单号查询亚马逊订单多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsByAmazonOrderId(List<String> list) {
    return this.baseMapper.getIdsByAmazonOrderId(list);
  }

  /**
   * 通过亚马逊订单主键查询订单号
   */
  @Override
  public String getAmazonOrderIdById(Long id) {
    return this.baseMapper.getAmazonOrderIdById(id);
  }

  /**
   * 通过亚马逊订单主键查询订单号列表
   */
  @Override
  public List<String> getAmazonOrderIdByIds(List<Long> ids) {
    List<Map<String, Object>> maps = this.baseMapper.getAmazonOrderIdByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap -> (String) stringObjectMap.get("amazonOrderId"))
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id 亚马逊订单的主键
   */
  @Override
  public AmazonOrderListVo getVoById(Long id) throws Exception {
    AmazonOrderListVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }

    AmazonOrderListProductSearchParamPo listSearchParamPo =
      new AmazonOrderListProductSearchParamPo();
    listSearchParamPo.setParentAmazonOrderList(id);
    listSearchParamPo.applySqlSegments();
    vo.setList(amazonOrderListProductService.search(listSearchParamPo));

    return vo;
  }

  /**
   * 分页查询亚马逊订单
   * @param search 查询条件
   * @return 亚马逊订单分页查询结果
   */
  @Override
  public Page<AmazonOrderListItemVo> pageSearch(
    AmazonOrderListSearchParamPo search
  ) {
    Page<AmazonOrderListItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(AmazonOrderListItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * 通用方法，为列表添加子表数据
   * @param pageResult 列表结果
   */
  protected Page<?> appendWithChild(Page<AmazonOrderListItemVo> pageResult) {
    Page<JSONObject> withChildPage = new Page<>(
      pageResult.getCurrent(),
      pageResult.getSize(),
      pageResult.getTotal()
    );
    withChildPage.setRecords(new ArrayList<>());
    for (AmazonOrderListItemVo itemVo : pageResult.getRecords()) {
      JSONObject itemJson = (JSONObject) JSONObject.toJSON(itemVo);
      withChildPage.getRecords().add(itemJson);

      AmazonOrderListProductSearchParamPo listSearchParamPo =
        new AmazonOrderListProductSearchParamPo();
      listSearchParamPo.setPageSize(200);
      listSearchParamPo.setParentAmazonOrderList(itemVo.getId());
      itemJson.put(
        "list",
        amazonOrderListProductService.pageSearch(listSearchParamPo)
      );
    }
    return withChildPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 亚马逊订单分页查询结果
   */
  @Override
  public Page<?> pageWithChildSearch(AmazonOrderListSearchParamPo search) {
    return appendWithChild(pageSearch(search));
  }

  /**
   * 仅获取子表的查询结果
   * @param parentId 主表编号
   * @param search 查询条件(仅使用分页参数，不处理其它条件)
   * @return
   */
  @Override
  public Page<?> pageOnlyChildSearch(
    Long parentId,
    AmazonOrderListSearchParamPo search
  ) {
    AmazonOrderListSearchParamPo parentSearchParam =
      new AmazonOrderListSearchParamPo();
    parentSearchParam.setIdEq(parentId);
    List<AmazonOrderListItemVo> parentList = search(parentSearchParam);
    if (parentList.size() > 0) {
      AmazonOrderListItemVo itemVo = parentList.get(0);

      AmazonOrderListProductSearchParamPo listSearchParamPo =
        new AmazonOrderListProductSearchParamPo();
      listSearchParamPo.setPageSize(search.getPageSize());
      listSearchParamPo.setCurrent(search.getCurrent());
      listSearchParamPo.setParentAmazonOrderList(itemVo.getId());
      return amazonOrderListProductService.pageSearch(listSearchParamPo);
    } else {
      return null;
    }
  }

  /**
   * 亚马逊订单快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'AmazonOrderListOptions::' + @userInfo.userTypeAndId + '::' + #search.keyword"
  )
  public List<OptionItem<AmazonOrderListItemVo>> searchOptions(
    AmazonOrderListSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询亚马逊订单
   * @param search 查询条件
   * @return 亚马逊订单列表查询结果
   */
  @Override
  public List<AmazonOrderListItemVo> search(
    AmazonOrderListSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询亚马逊订单最后更新时间
   * @param search 查询条件
   * @return 亚马逊订单最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(AmazonOrderListSearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }

  /**
   * 根据日期同步
   */
  /**
   * 根据日期同步表单确定操作
   */
  @Override
  public void syncByTimeConfirm(JSONObject data) throws Exception {
    executeScriptEngine.callJsInResource(
      "scripts/AmazonOrderList_syncByTime_confirm.js",
      data,
      this
    );
  }

  /**
   * 同步数据
   */
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void syncData() throws Exception {
    executeScriptEngine.callJsInResource(
      "scripts/AmazonOrderList_syncData.js",
      null,
      null,
      this
    );
  }

  /**
   * 标记推广
   */
  @Override
  public void aolSignPromotion(List<Long> ids) throws Exception {
    if (amazonOrderListAolSignPromotionAction == null) {
      throw new Exception("此操作当前不可用");
    }
    amazonOrderListAolSignPromotionAction.run(ids);
  }

  /**
   * 销售订单
   */
  @Override
  public List<AmazonOrderListItemVo> sellOrder(
    AmazonOrderListSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.sellOrder(search);
  }

  /**
   * 销售订单分页
   */
  @Override
  public Page<AmazonOrderListItemVo> sellOrderPage(
    AmazonOrderListSearchParamPo search
  ) {
    Page<AmazonOrderListItemVo> sellOrderPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return sellOrderPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return sellOrderPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    sellOrderPage = this.baseMapper.sellOrderPage(search.toPage(), search);
    List<Long> recordIds = sellOrderPage
      .getRecords()
      .stream()
      .map(AmazonOrderListItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return sellOrderPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return sellOrderPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    sellOrderPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return sellOrderPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 亚马逊订单分页查询结果
   */
  @Override
  public Page<?> sellOrderPageWithChildSearch(
    AmazonOrderListSearchParamPo search
  ) {
    return appendWithChild(sellOrderPage(search));
  }

  /**
   * 查询销售订单最后更新时间
   * @param search 查询条件
   * @return 销售订单最后更新时间
   */
  @Override
  public Date sellOrderLastUpdateTime(AmazonOrderListSearchParamPo search) {
    return this.baseMapper.sellOrderLastUpdateTime(search);
  }

  /**
   * 多渠道订单
   */
  @Override
  public List<AmazonOrderListItemVo> multiChannel(
    AmazonOrderListSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.multiChannel(search);
  }

  /**
   * 多渠道订单分页
   */
  @Override
  public Page<AmazonOrderListItemVo> multiChannelPage(
    AmazonOrderListSearchParamPo search
  ) {
    Page<AmazonOrderListItemVo> multiChannelPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return multiChannelPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return multiChannelPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    multiChannelPage =
      this.baseMapper.multiChannelPage(search.toPage(), search);
    List<Long> recordIds = multiChannelPage
      .getRecords()
      .stream()
      .map(AmazonOrderListItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return multiChannelPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return multiChannelPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    multiChannelPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return multiChannelPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 亚马逊订单分页查询结果
   */
  @Override
  public Page<?> multiChannelPageWithChildSearch(
    AmazonOrderListSearchParamPo search
  ) {
    return appendWithChild(multiChannelPage(search));
  }

  /**
   * 查询多渠道订单最后更新时间
   * @param search 查询条件
   * @return 多渠道订单最后更新时间
   */
  @Override
  public Date multiChannelLastUpdateTime(AmazonOrderListSearchParamPo search) {
    return this.baseMapper.multiChannelLastUpdateTime(search);
  }
}
